#!/usr/bin/perl

use strict;
use warnings FATAL => 'all';

use Getopt::Long;

my ($user, $group);

sub usage {
	die "Usage: $0 -u user -g group -- command arguments\n";
}

GetOptions(
	'user=s' => \$user,
	'group=s' => \$group,
) or usage;

if (not defined $user or not @ARGV) {
	usage;
}

my (undef, undef, $uid, $gid) = getpwnam($user);
if (defined $group) {
	(undef, undef, $gid) = getgrnam($group);
}

$( = $gid;
if ($( != $gid) {
	die "Error setting real id to [$gid]\n";
}
$) = "$gid $gid";
$> = $< = $uid;
if ($< != $uid) {
	die "Error setting real uid to [$uid]\n";
}

exec @ARGV;
